package momo.app.status;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StatusListener extends Thread
{
	private Log log = LogFactory.getLog(StatusListener.class);
	
	private final int TIMEOUT = 5 * 60 * 1000;
	private boolean isListening;
	
	private ServerSocket server;
	private int port;
	
	public StatusListener(int port)
	{
		this.port = port;
		isListening = true;
		this.start();
	}
	
	public void run()
	{
		if ( log.isDebugEnabled() )
			log.debug("Status Server starts");
		try
		{
			server = new ServerSocket();
//			server.bind(new InetSocketAddress(InetAddress.getByName(Config.getIPAddress()), port));
			server.bind(new InetSocketAddress(port));
			server.setSoTimeout(TIMEOUT);
			
			while ( isListening )
			{
				try
				{
					Socket sock = null;
					while( (sock = server.accept()) != null )
					{
						new StatusHandler(sock);
					}
				}catch(SocketTimeoutException ste)
				{
					if ( log.isDebugEnabled() )
						log.debug("SocketTimeoutException", ste);
				}catch(Exception e)
				{
					if ( log.isErrorEnabled() )
						log.error("Exception", e);
					stopListening();
				}
			}
		}catch(Exception e)
		{
			if ( log.isErrorEnabled() )
				log.error("Exception", e);
			stopListening();
		}
		
		if ( log.isDebugEnabled() )
			log.debug("Status Server en	ds");
	}
	
	public void stopListening()
	{
		isListening = false;
		try
		{
			server.close();
		}catch (Exception e)
		{
			if ( log.isErrorEnabled() )
				log.error("Exception", e);
		}
	}
	
}//end of StatusListener